using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Design;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;

namespace Matrix.Configuration
{
    /// <summary>
    /// 设计时DbContext工厂，用于EF Core迁移
    /// </summary>
    public class DesignTimeDbContextFactory : IDesignTimeDbContextFactory<MatrixConfigurationDbContext>
    {
        public MatrixConfigurationDbContext CreateDbContext(string[] args)
        {
            var configuration = BuildConfiguration();

            var builder = new DbContextOptionsBuilder<MatrixConfigurationDbContext>();
            builder.UseNpgsql(configuration.GetConnectionString("Default"));

            return new MatrixConfigurationDbContext(builder.Options);
        }

        private IConfigurationRoot BuildConfiguration()
        {
            var builder = new ConfigurationBuilder()
                .SetBasePath(Directory.GetCurrentDirectory())
                .AddJsonFile("appsettings.json", optional: true)
                .AddJsonFile("appsettings.Development.json", optional: true)
                .AddEnvironmentVariables();

            return builder.Build();
        }
    }
}